/* generate_sigma.c -- generate interpolation table for sigmoidal function
 * copyright (c) 2003-2005 Peter van Rossum <petervr@users.sourceforge.net>
 * released under the GNU Lesser General Public License
 * $Id: generate_sigma.c,v 1.13 2005/07/11 15:44:49 petervr Exp $ */

#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

/****************************************
 * Settable parameters
 ****************************************/

float min_entry = -12.0;        /* first entry in the table, switch -f */
float max_entry = 12.0;         /* last entry in the table, switch -l */
int num_entries = 2000;         /* number of entries in the table, switch -n */

int
parse (int argc, char *argv[])
{
  char c;
  while ((c = getopt (argc, argv, "f:l:n:h")) != -1) {
    switch (c) {
    case 'h':
      printf ("Usage: generate_sigma [OPTIONS]\n");
      printf
        ("Generate an interpolation table for s(x) = 1/(1+exp(-x)).\n\n");
      printf ("  -f first entry of table\n");
      printf ("  -l last entry of table\n");
      printf ("  -n number of entries in table\n");
      printf ("  -h this help\n");
      return 0;
      break;
    case 'f':
      if (sscanf (optarg, "%f", &min_entry) == 0)
        return 0;
      break;
    case 'l':
      if (sscanf (optarg, "%f", &max_entry) == 0)
        return 0;
      break;
    case 'n':
      if (sscanf (optarg, "%i", &num_entries) == 0)
        return 0;
      break;
    default:
      printf ("Try `generate_sigma -h' for more information.\n");
      exit (1);
    }
  }
  return 1;
}

/****************************************
 * Main
 ****************************************/

int
main (int argc, char *argv[])
{
  int i;
  float x, y;
  float interval = (max_entry - min_entry) / (num_entries - 1);

  if (parse (argc, argv) == 0)
    return 0;

  printf ("/* interpolation.c - interpolation table for sigmoidal function\n");
  printf (" * copyright (c) 2003-2005 Peter van Rossum");
  printf (" <petervr@users.sourceforge.net>\n");
  printf (" * released under the GNU Lesser General Public License\n");
  printf (" * automatically generated by generate_sigma */\n\n");
  printf ("static const float min_entry = %.20f;\n", min_entry);
  printf ("static const float max_entry = %.20f;\n", max_entry);
  printf ("static const int num_entries = %i;\n", num_entries);
  printf ("static const float interval = %.20f;\n", interval);
  printf ("static const float interpolation[%i] = {\n", num_entries);
  for (i = 0; i < num_entries; i++) {
    x = interval * i + min_entry;
    y = 1.0 / (1.0 + exp (-x));
    printf ("  %.20f%s\n", y, i == num_entries - 1 ? "" : ",");
  }
  printf ("};\n");

  return 0;
}
